package com.js.data.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.js.data.common.constant.SymbolConstant;
import com.js.data.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;


/**
 *
 */
@Configuration
public class MybatisPlusFillHandler implements MetaObjectHandler {

    private final static String CREATE_TIME_STR = "createTime";

    private final static String UPDATE_TIME_STR = "updateTime";
    private final static String CREATE_BY_STR = "createBy";

    private final static String UPDATE_BY_STR = "updateBy";

    private final static String CREATE_NAME_STR = "createName";

    private final static String DEL_FLAG_STR = "delFlag";


    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        Long userId = getUserId();
        setFill(metaObject, CREATE_BY_STR, userId);
        setFill(metaObject, CREATE_TIME_STR, now);
        setFill(metaObject, UPDATE_BY_STR, userId);
        setFill(metaObject, UPDATE_TIME_STR, now);
        setFill(metaObject, DEL_FLAG_STR, SymbolConstant.ZERO_INT);
        if (metaObject.hasSetter(CREATE_NAME_STR)) {
            setFieldValByName(CREATE_NAME_STR, SecurityUtils.getCurrentUsername(), metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        Long userId = getUserId();
        setFill(metaObject, UPDATE_BY_STR, userId);
        setFill(metaObject, UPDATE_TIME_STR, now);
    }

    private void setFill(MetaObject metaObject, String key, Object value) {
        if (metaObject.hasSetter(key)) {
            setFieldValByName(key, value, metaObject);
        }
    }

    private Long getUserId() {
        try {
            return SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            return 0L;
        }
    }

}
